/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.colswe.testingProject.view;

import java.awt.Container;
import java.util.Collection;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.colswe.testingProject.control.SystemRolesControl;
import org.colswe.testingProject.control.SystemUserControl;
import org.colswe.testingProject.entity.SystemRoles;
import org.colswe.testingProject.entity.SystemUser;

/**
 *
 * @author andres
 */
public class UserAdministration extends javax.swing.JPanel {

    SystemUserControl suc;

    /**
     * Creates new form UserAdministration
     */
    public UserAdministration() {
        suc = new SystemUserControl();
        initComponents();
    }

    private ComboBoxModel generateModel() {
        Collection<SystemRoles> roles = new SystemRolesControl().readAll();
        String[] data;
        data = new String[roles.size()];
        int i = 0;
        for (SystemRoles sr : roles) {
            data[i] = sr.getName();
            i++;
        }
        return new DefaultComboBoxModel(data);
    }

    private TableModel genTableModel() {
        Collection<SystemUser> users = new SystemUserControl().readAll();
        String data[][];
        String[] columnNames = {"Rol", "Usuario"};
        data = new String[users.size()][2];
        int i = 0;
        for (SystemUser su : users) {
            data[i][0] = su.getUserRole().getName();
            data[i][1] = su.getUserName();
            i++;
        }
        return new DefaultTableModel(data, columnNames);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblUsers = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        txtUserName = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        cmbRole = new javax.swing.JComboBox();
        btnFilter = new javax.swing.JButton();
        btnCreate = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();

        setMaximumSize(new java.awt.Dimension(730, 650));
        setMinimumSize(new java.awt.Dimension(730, 650));
        setPreferredSize(new java.awt.Dimension(730, 650));

        tblUsers.setModel(genTableModel());
        jScrollPane1.setViewportView(tblUsers);

        jLabel1.setText("Usuario");

        jLabel2.setText("Rol");

        cmbRole.setModel(generateModel());

        btnFilter.setText("Filtrar");
        btnFilter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFilterActionPerformed(evt);
            }
        });

        btnCreate.setText("Crear");
        btnCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCreateActionPerformed(evt);
            }
        });

        btnEdit.setText("Editar");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });

        btnDelete.setText("Eliminar");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmbRole, javax.swing.GroupLayout.PREFERRED_SIZE, 322, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnFilter))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 673, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addComponent(btnCreate)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnEdit)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDelete)))
                .addGap(0, 45, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel1)
                    .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnFilter)
                    .addComponent(jLabel2)
                    .addComponent(cmbRole, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCreate)
                    .addComponent(btnEdit)
                    .addComponent(btnDelete))
                .addContainerGap(124, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
        SystemUser toEdit = null;
        Collection<SystemUser> user = suc.readAll();
        String which = (String) tblUsers.getValueAt(tblUsers.getSelectedRow(), 1);
        for (SystemUser sr : user) {
            if (sr.getUserName().equals(which)) {
                toEdit = sr;
            }
        }
        Container parent = getParent();
        parent.setVisible(false);
        parent.removeAll();
        parent.add(new SystemUserEdit(toEdit));
        parent.setVisible(true);
    }//GEN-LAST:event_btnEditActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        SystemUser toDelete = null;
        Collection<SystemUser> user = new SystemUserControl().readAll();
        String which = (String) tblUsers.getValueAt(tblUsers.getSelectedRow(), 1);
        for (SystemUser sr : user) {
            if (sr.getUserName().equals(which)) {
                toDelete = sr;
            }
        }
        if (suc.delete(toDelete)) {
            JOptionPane.showMessageDialog(this, "Eliminado correctamente", "Información", JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(this, "No se ha completado correctamente", "Error", JOptionPane.ERROR_MESSAGE);
        }
        tblUsers.setModel(genTableModel());
    }//GEN-LAST:event_btnDeleteActionPerformed

    private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateActionPerformed
        Container parent = getParent();
        parent.setVisible(false);
        parent.removeAll();
        parent.add(new SystemUserEdit(null));
        parent.setVisible(true);
    }//GEN-LAST:event_btnCreateActionPerformed

    private void btnFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFilterActionPerformed
        Collection<SystemUser> user = new SystemUserControl().readAll();
        String[][] data;
        String[] columns;
        data = new String[user.size()][2];
        columns = new String[]{"Rol", "Usuario"};
        int i = 0;
        if (!txtUserName.getText().equals("")) {
            for (SystemUser su : user) {
                if (su.getUserName().equalsIgnoreCase(txtUserName.getText())) {
                    data[i][0] = su.getUserRole().getName();
                    data[i][1] = su.getUserName();
                    i++;
                }
            }
        } else {
            System.out.println(cmbRole.getSelectedItem());
            for (SystemUser su : user) {
                if (su.getUserRole().getName().equals((String) cmbRole.getSelectedItem())) {
                    data[i][0] = su.getUserRole().getName();
                    data[i][1] = su.getUserName();
                    i++;
                }
            }
        }
        tblUsers.setModel(new DefaultTableModel(data, columns));
    }//GEN-LAST:event_btnFilterActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCreate;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnFilter;
    private javax.swing.JComboBox cmbRole;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblUsers;
    private javax.swing.JTextField txtUserName;
    // End of variables declaration//GEN-END:variables
}
